<template>
    <div>
        <van-nav-bar title="修改密码" left-text="返回" left-arrow @click-left="proxy.$leftClick()" />
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    修改
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onBeforeMount,ref } from 'vue';
import { useRouter } from 'vue-router';
import { changeName,getMyInfo } from '@/api/user';
import { showDialog } from 'vant';
const { proxy }: any = getCurrentInstance();
const router = useRouter()
let username = ref('');


onBeforeMount(async () => {
    if(!localStorage.getItem("userId")){
        router.push({name:'denglu'})
    }
    let res  =await getMyInfo(localStorage.getItem("userId") as string);
    console.log(res);
    
    if((res.data[0].username).trim().length !=0){
        username.value = res.data[0].username;
    }else{
        username.value = '请输入用户名'
    }
})

const onSubmit = async()=>{
    await changeName(localStorage.getItem("userId") as string,username.value);
    showDialog({
        message:"修改成功"
    });
    router.push({name:'my'})
}
</script>